import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { loadableReady } from '@loadable/component'

import configureStore from '../redux/configureStore'
import createReducer from '../redux/createReducer'

const render = ({ App, actions }) => {
  /* ----------- read __DATA__ from window ---------- */
  const data = typeof window.__DATA__ === 'string' ? {} : window.__DATA__;
  /* ------------------------------------------------ */

  const rootReducer = createReducer(actions)
  const store = configureStore(rootReducer, data)

  const AppComponent = props => (
    <BrowserRouter>
      <Provider store={store}>
        <App />
      </Provider>
    </BrowserRouter>
  )

  const dom = document.getElementById('root')

  loadableReady(() => {
    typeof window.__DATA__ === 'string'
      ? ReactDOM.render(<AppComponent />, dom)
      : ReactDOM.hydrate(<AppComponent />, dom)
  })
}

export default render

